package com.hmall.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {

    //在Controller之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取登录用户的信息
        String userInfo = request.getHeader("user-info");
        // 2.判断是否获取了用户，因为有的接口不需要登录就能访问；如果有，存入ThreadLocal
        if (StrUtil.isNotBlank(userInfo)){

            UserContext.setUser(Long.valueOf(userInfo));

        }

        // 3.放行
        return true;
    }

    //在Controller之后执行，清理用户信息
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理用户信息
        UserContext.removeUser();
    }
}
